#include <WiFi.h>
#include "PubSubClient.h"
#include <SimpleDHT.h>
#include "BH1750.h"
#include "Wire.h"
BH1750 bh1750_a;
BH1750 bh1750_b;
const char* ssid = "Mi13";                  
const char* password = "12341234";          
const char* mqtt_server = "bemfa.com";       
const int mqtt_server_port = 9501;     
#define ID_MQTT  "f086f7482a4045b4a9cad88f783976c5"   
const char*  topic = "kzpin";                      
const char * dhttopic = "temp004";               
int pinDHT11 = 16;                         
int zlpin = 17;
int jspin = 4; 
int jrpin = 5; 
long timeval = 2 * 1000;            


String zlstatus = "zloff";
String jsstatus = "jsoff";
String jrstatus = "jroff";
long lastMsg = 0;
SimpleDHT11 dht11(pinDHT11);//dht11初始化
WiFiClient espClient;
PubSubClient client(espClient);//mqtt初始化


//灯光函数及引脚定义
void turnOnjs();
void turnOffjs();
void turnOnzl();
void turnOffzl();
void turnOnjr();
void turnOffjr();


void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String Mqtt_Buff = "";
  for (int i = 0; i < length; i++) {
    Mqtt_Buff += (char)payload[i];
  }
  Serial.print(Mqtt_Buff);
  Serial.println();

  // Switch on the LED if an 1 was received as first character控制继电器
  if (Mqtt_Buff == "json") {
    turnOnjs();
  } else if (Mqtt_Buff == "jsoff") {
    turnOffjs();
  }
    else if (Mqtt_Buff == "zlon") {
    turnOnzl();
  } else if (Mqtt_Buff == "zloff") {
    turnOffzl();
  }
    else if (Mqtt_Buff == "jron") {//控制加热
    turnOnjr();
  } else if (Mqtt_Buff == "jroff") {
    turnOffjr();
  }
  Mqtt_Buff = "";
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(ID_MQTT)) {//连接mqtt
      Serial.println("connected");
      client.subscribe(topic);//修改，修改为你的主题
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}


void setup() {
  pinMode(zlpin, OUTPUT);
  pinMode(jspin, OUTPUT);
  pinMode(jrpin, OUTPUT);
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, mqtt_server_port);
  client.setCallback(callback);
  digitalWrite(zlpin, LOW);
  digitalWrite(jspin, LOW);
  digitalWrite(jrpin, LOW);
  Wire.begin(18, 19);
  Wire1.begin(21, 22);
  bh1750_a.begin(BH1750::CONTINUOUS_HIGH_RES_MODE, 0x23, &Wire);
  bh1750_b.begin(BH1750::CONTINUOUS_HIGH_RES_MODE, 0x23, &Wire1);
}
int error_counter_1_b = 0;
int error_counter_2_b = 0;
void loop() {
  if (!client.connected()) {//判断mqtt是否连接
    reconnect();
  }
  client.loop();//mqtt客户端


  long now = millis();//获取当前时间戳
  if (now - lastMsg > timeval) {//如果达到3s，进行数据上传
    lastMsg = now;
    

    // read without samples.
    byte temperature = 0;
    byte humidity = 0;
    int err = SimpleDHTErrSuccess;
    if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
      Serial.print("Read DHT11 failed, err="); Serial.println(err); delay(1000);
      return;
    }
    //光照
    float light_level_b;
    if (bh1750_b.measurementReady()) {
    light_level_b = bh1750_b.readLightLevel();
    
  }
    if (lround(light_level_b) == -1) {
    error_counter_1_b++;
  }
  if (lround(light_level_b) == -2) {
    error_counter_2_b++;
  }
    String  msg = "#" + (String)temperature + "#" + (String)humidity + "#" + (String)light_level_b+"#"+ jsstatus+"#"+zlstatus+"#"+jrstatus+"#"; //数据封装#温度#湿度#光照强度#加湿状态#制冷状态#
    client.publish(dhttopic, msg.c_str());//数据上传
  }



}

//打开加湿
void turnOnjs() {
  jsstatus = "json";
  Serial.println("turn on 加湿");
  digitalWrite(jspin, HIGH);
}
//关闭加湿
void turnOffjs() {
  jsstatus = "jsoff";
  Serial.println("turn off 加湿");
  digitalWrite(jspin, LOW);
}
//打开制冷
void turnOnzl() {
  zlstatus = "zlon";
  Serial.println("turn on 制冷");
  digitalWrite(zlpin, HIGH);
}
//关闭制冷
void turnOffzl() {
  zlstatus= "zloff";
  Serial.println("turn off 制冷");
  digitalWrite(zlpin, LOW);
}
//打开加热
void turnOnjr() {
  jrstatus = "jron";
  Serial.println("turn on 加热");
  digitalWrite(jrpin, HIGH);
}
//关闭加热
void turnOffjr() {
  jrstatus= "jroff";
  Serial.println("turn off 加热");
  digitalWrite(jrpin, LOW);
}
